package com.chapter.sample.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.chapter.sample.anno.MyMapperScan;
import com.chapter.sample.imports.MyImportBeanDefinitionRegistrar;
import com.chapter.sample.imports.MyImportSelector;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;

import javax.sql.DataSource;

@Configuration // 标注当前类是配置类 （替代配置文件） + @Component
//<context:component-scan base-package="com.chapter.sample"/>
@ComponentScan("com.chapter.sample")
//<context:property-placeholder location="classpath:jdbc.properties"/>
@PropertySource("classpath:jdbc.properties")

@MapperScan("com.chapter.sample.mapper")

//@Import(MyImportSelector.class)
//@Import(MyImportBeanDefinitionRegistrar.class)
@MyMapperScan
public class SpringConfig {


    @Bean
    public DataSource dataSource(@Value("${jdbc.driver}") String driver,
                                 @Value("${jdbc.url}") String url,
                                 @Value("${jdbc.username}") String username,
                                 @Value("${jdbc.password}") String password){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }


    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }

}
